package site;

import java.io.IOException;
import java.util.ArrayList;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SConnexion
 */
public class SConnexion extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	ConnexionManager cm ;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SConnexion() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String login = (String)request.getParameter("login");
		String password = (String)request.getParameter("password");
		ArrayList<Integer> l = cm.getIdLogin(login) ;
		ArrayList<Integer> p = cm.getIdPW(password) ;
		if (!l.isEmpty() && !p.isEmpty() && p.get(0)==l.get(0)) {
		HttpSession session = request.getSession();
		session.setAttribute("login", login);
		session.setAttribute("password", password);
		
		
		//La gestion du cookie
		if(request.getParameter("auto_connect") != null){
			Cookie loginCookie = new Cookie("login", login);
			Cookie passwordCookie = new Cookie("password", password);
			response.addCookie(loginCookie);
			response.addCookie(passwordCookie);
		}
		session.setAttribute("nom",cm.getNom(login)) ;
		session.setAttribute("prenom",cm.getPrenom(login)) ;
		session.setAttribute("connexion", true);
		if (!(Boolean) getServletContext().getAttribute("nouveau")) {
			request.getRequestDispatcher("PageInitiale.jsp").forward(request, response);
		}
		else {
			request.getRequestDispatcher("ComplementForm.html").forward(request, response);
		}
		}
		else {
			getServletContext().setAttribute("etat","Erreur d'authentification!!!!");
			request.getRequestDispatcher("Connexion.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
